import { Form, Drawer, Row, Col, Input, InputNumber, Space, Button, Divider, Select } from 'antd';
import { useEffect, useState } from 'react';
import { connect } from 'umi';
import { normFile, uuid } from '@/utils/upload';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import AliyunOSSUpload from '@/components/AliyunOSSUpload/App';
import AliyunOSSBraftEditor from '@/components/AliyunOSSBraftEditor/App';
import styles from '../styles.less';

const DataForm = (props) => {
  const { dispatch, submitting } = props;
  const { dataForm, setDataForm, tablePayload, setTablePayload } = props.data;
  const [form] = Form.useForm();
  const [readingEditorState, setReadingEditorState] = useState(null);
  const [img, setImg] = useState([]);
  const [detail, setDetail] = useState([]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({ status: 0, sellStatus: 1, orderby: 0, sellNum: 0, virtualNum: 0 });
    }

    if (dataForm && dataForm.data) {
      let img_ = [];
      if (dataForm.data.img) {
        img_ = [{ uuid: uuid(), name: dataForm.data.img.split('/').pop(), status: 'done', url: dataForm.data.img }];
      }
      setImg(img_);

      let detail_ = [];
      if (dataForm.data.detail) {
        detail_ = JSON.parse(dataForm.data.detail).map(d => {
          return { uuid: uuid(), name: d.split('/').pop(), status: 'done', url: d };
        });
      }
      setDetail(detail_);

      form.setFieldsValue({
        ...dataForm.data,
        reading: BraftEditor.createEditorState(dataForm.data.reading),
        img: img_,
        detail: detail_,
      });
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      values.reading = readingEditorState ? readingEditorState.toHTML() : '';

      if (values.img && (values.img.length > 0)) {
        values.img = values.img.filter(d => d.status === 'done').pop().url;
      } else {
        values.img = '';
      }

      if (values.detail) {
        values.detail = JSON.stringify(values.detail.filter(d => d.status === 'done').map(d => d.url));
      } else {
        values.detail = '[]';
      }

      dispatch({
        type: values.id ? 'PMallPkg/edit' : 'PMallPkg/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({ ...tablePayload });
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
    setImg([]);
    setDetail([]);
  }

  return (
    <Drawer
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onClose={onCancel}
      forceRender={true}
      width={'calc(100% - 215px)'}
      headerStyle={{ padding: '8px 24px' }}
      bodyStyle={{ paddingBottom: 80 }}
      extra={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button loading={submitting} onClick={onOk} type="primary">提交</Button>
        </Space>
      }
    >
      <Form layout="horizontal" labelCol={{ span: 4 }} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
        )}
        <Form.Item name="status" hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item name="sellStatus" hidden={true}>
          <Input />
        </Form.Item>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="name" label="套餐名称"
              rules={[
                { required: true, message: '套餐名称不能为空' },
              ]}>
              <Input placeholder="请输入套餐名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="description" label="套餐说明"
              rules={[
                { required: true, message: '套餐说明不能为空' },
              ]}>
              <Input placeholder="请输入套餐说明" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="rawSellPrice" label="售价"
              rules={[
                { required: true, message: '售价不能为空' },
              ]}>
              <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入售价" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="rawMarketPrice" label="市场价"
              rules={[
                { required: true, message: '市场价不能为空' },
              ]}>
              <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入市场价" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="rawCostPrice" label="成本价"
              rules={[
                { required: true, message: '成本价不能为空' },
              ]}>
              <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入成本价" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="stock" label="现有库存"
              rules={[
                { required: true, message: '现有库存不能为空' },
              ]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入现有库存" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="sellNum" label="真实销量"
              rules={[
                { required: true, message: '真实销量不能为空' },
              ]}>
              <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入真实销量" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="virtualNum" label="虚拟销量"
              rules={[
                { required: true, message: '虚拟销量不能为空' },
              ]}>
              <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入虚拟销量" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="indate" label="有效期天" tooltip="购买后多少天有效，为 0 时永久有效"
              rules={[
                { required: true, message: '有效期不能为空' },
              ]}>
              <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入有效期，为 0 永久有效" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="orderby" label="排序属性"
              rules={[
                { required: true, message: '排序属性不能为空' },
              ]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入排序属性" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="limitType" label="限购类型"
              rules={[
                { required: true, message: '限购类型不能为空' },
              ]}
            >
              <Select placeholder="请选择限购类型">
                <Select.Option value={0}>不限购</Select.Option>
                <Select.Option value={1}>每天</Select.Option>
                <Select.Option value={2}>每周</Select.Option>
                <Select.Option value={3}>每月</Select.Option>
                <Select.Option value={4}>每年</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="limitNum" label="限购次数" tooltip="为 0 时，表示不限购"
              rules={[
                { required: true, message: '限购次数不能为空' },
              ]}>
              <InputNumber min={0} style={{ width: '100%' }} placeholder="请输入限购次数，为 0 不限购" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="remark" label="备注信息"
              rules={[
                { required: false, message: '备注信息不能为空' },
              ]}
            >
              <Input.TextArea placeholder="请输入备注信息" />
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{ marginTop: 0 }} />
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{ span: 2 }}
              name={'img'}
              label="宣传图片"
              rules={[
                { required: true, message: '宣传图片不能为空' },
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{ images: img, setImages: setImg, size: 10, len: 1, accept: 'image/*' }} />
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{ marginTop: -8 }} />
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              className={styles.editor_H150}
              labelCol={{ span: 2 }}
              name="reading" label="购买须知"
              rules={[
                { required: false, message: '购买须知不能为空' },
              ]}>
              <AliyunOSSBraftEditor data={{ setEditorState: setReadingEditorState }} />
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{ marginTop: 0 }} />
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{ span: 2 }} tooltip="宽750px，大小5M内"
              name={'detail'}
              label="套餐详情"
              rules={[
                { required: false, message: '套餐详情不能为空' },
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{ images: detail, setImages: setDetail, size: 5, len: 20, accept: 'image/*' }} />
            </Form.Item>
          </Col>
        </Row>

      </Form>
    </Drawer>
  );
};


export default connect(({ loading }) => {
  return {
    submitting: loading.effects['PMallPkg/add'] || loading.effects['PMallPkg/edit'],
  };
})(DataForm);

